//
//  SecondViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/9.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "SecondViewController.h"
#import "FindTableViewCell.h"
#import "BottomView.h"
#import <AFNetworking.h>
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "MyHomePageViewController.h"
#import <MBProgressHUD.h>
#import <UIButton+AFNetworking.h>
@interface SecondViewController ()<UITableViewDelegate,UITableViewDataSource,BottomViewDelegate,FindTableViewCellProtocol>{
    NSIndexPath *_selectedIndexPath;
    
}

@end


static NSString *reuseIdentify = @"cell";
@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self setupUI];
    
    _viewModel = [[FindViewModel alloc] init];
    
   
//    RAC(_findButton,enabled) = [RACSignal combineLatest:@[_textField.rac_textSignal] reduce:^id(NSString *text){
//        return @([text length]);
//        
//    }];
    
    @weakify(self);
    [[_findButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        
        
        [self.viewModel fetchDataWithUserName:self.textField.text];
    }];
    
    [[RACObserve(_viewModel,hasLoaded) deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        [self.tableView reloadData];
    }];
    
    
    [[RACObserve(_viewModel, isEmpty) deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        
        if ([x intValue] ==0) {
            return ;
        }
        @strongify(self);
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"没有该主持人的信息";
        [self.view addSubview:hud];
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
            
        }];
    }];
    
    [_viewModel fetchDataWithUserName:@""];
   
    
}


- (void)setupUI{
    _selectedIndexPath = nil;
    
    _searchView.layer.borderWidth = .8f;
    _searchView.layer.borderColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _searchView.layer.cornerRadius = 13.0f;
    _searchView.layer.masksToBounds = YES;
    
    
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    UINib *nib = [UINib nibWithNibName:@"FindTableViewCell" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:reuseIdentify];
    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat bottomHeight = 0;
    if (_selectedIndexPath && _selectedIndexPath == indexPath){
        bottomHeight = 30;
    }
    return 100+bottomHeight;
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_viewModel numberOfTable];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify];
    if (!cell) {
        cell = [[FindTableViewCell alloc] init];
    }
    NSDictionary *dic = [_viewModel dictionaryAtIndexPath:indexPath];
    
    cell.nameLabel.text = [dic objectForKey:@"nickname"];
    id sign = [dic objectForKey:@"sign"];
    cell.signLabel.text = [sign isKindOfClass:[NSNull class]]?@"欢迎使用婚礼人":sign;
    
    cell.phoneString = [dic objectForKey:@"phone"];
    id age = [dic objectForKey:@"age"];
    cell.ageLabel.text = [NSString stringWithFormat:@"%@",age];
    cell.username = [dic objectForKey:@"username"];
    cell.delegate = self;
    [cell.avatarButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[dic objectForKeyedSubscript:@"avatar"]] placeholderImage:[UIImage imageNamed:@"touxiang.jpg"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_selectedIndexPath && _selectedIndexPath == indexPath) {
        
        
        
        BottomView *bottomView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([BottomView class]) owner:self options:nil] lastObject];
        [bottomView setTranslatesAutoresizingMaskIntoConstraints:NO];
        bottomView.phone = cell.phoneString;
        bottomView.username = cell.username;
        
        
        bottomView.delegate = self;
        
        
        [cell addSubview:bottomView];
        
        NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:bottomView.superview attribute:NSLayoutAttributeLeading multiplier:1 constant:0];
        NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:bottomView.superview attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];
        
        
        NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:bottomView.superview attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
        NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:30];
        [bottomView addConstraint:height];
        
        
        [cell addConstraint:bottom];
        [cell addConstraint:trailing];
        [cell addConstraint:leading];
       
        
    
        cell.arrowImage.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI/180*180);
        
    }else{
        for (UIView *view in [cell subviews]) {
            if ([view isKindOfClass:[BottomView class]]) {
                [view removeFromSuperview];
            }
        }
        cell.arrowImage.transform = CGAffineTransformRotate(CGAffineTransformIdentity, 0);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (_selectedIndexPath==nil) {
        _selectedIndexPath = indexPath;
        
        
        [tableView beginUpdates];
     
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        [tableView endUpdates];
        
    }else if(_selectedIndexPath != indexPath){
        NSIndexPath *tempIndexPath = _selectedIndexPath;
        
        _selectedIndexPath = indexPath;
        [tableView beginUpdates];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tempIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView endUpdates];
        
        [tableView beginUpdates];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_selectedIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView endUpdates];
        
    
    }else{
        _selectedIndexPath = nil;
        [tableView beginUpdates];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView endUpdates];
    }
}

#pragma bottom delegate

- (void)callPhone:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

- (void)collectUser:(NSString *)user{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.mode = MBProgressHUDModeText;
    [self.view addSubview:hud];
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id token = [userDefaults objectForKey:@"token"];
    if (!token) {
        hud.labelText = @"亲，请先登录";
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        }];
        return;
    }
    
    
    
    hud.labelText = @"正在收藏";
    [hud show:YES];
    [[FindViewModel collectUser:user] subscribeNext:^(id x) {
        hud.labelText = @"收藏成功";
        [hud hide:YES afterDelay:1];
    } error:^(NSError *error) {
        hud.labelText = @"发生错误";
        [hud hide:YES afterDelay:1];
    }];

}


- (void)viewUser:(NSString *)username{

    MyHomePageViewController *homePage = [[MyHomePageViewController alloc] initWithNibName:NSStringFromClass([MyHomePageViewController class]) bundle:nil];
    homePage.username = username;
    
    [self presentViewController:homePage animated:YES completion:nil];
    
}
@end
